package top.riske.animalhazardassessment.analyse.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import top.riske.animalhazardassessment.ai.DataReceivedCallback;
import top.riske.animalhazardassessment.ai.DeepSeekService;
import top.riske.animalhazardassessment.analyse.service.AnalyseService;
import top.riske.animalhazardassessment.common.DTO.AnalyseDto;
import top.riske.animalhazardassessment.common.entity.Analyse;
import top.riske.animalhazardassessment.common.entity.Animal;
import top.riske.animalhazardassessment.common.entity.Species;
import top.riske.animalhazardassessment.common.http.request.AnalyseRequest;
import top.riske.animalhazardassessment.common.mapper.AnalyseMapper;
import top.riske.animalhazardassessment.common.mapper.AnimalMapper;
import top.riske.animalhazardassessment.common.mapper.SpeciesMapper;
import top.riske.animalhazardassessment.common.utils.RequestUtils;

import java.util.List;
import java.util.Map;

@Tag(name = "AnalyseController",description = "分析动物危险性")
@Slf4j
@RestController
public class AnalyseController {

    @Resource
    private AnalyseService analyseService;

    @Resource
    private SpeciesMapper speciesMapper;

    @Resource
    private AnimalMapper animalMapper;

    @Resource
    private AnalyseMapper analyseMapper;

    @Resource
    private DeepSeekService deepSeekService;

    @Resource
    private ObjectMapper oobjectMapper;

    @Operation(summary = "根据宠物狗数据，分析评估危险性")
    @GetMapping("/analyse/dog")
    public AnalyseDto analyseDogHazard(@Parameter(description = "宠物狗数据，animalId可选，传递后会使计算得到的结果绑定到动物数据中，带risk后缀的是计算后返回的结果，不需要传递") AnalyseDto analyse) {
        double risk = analyseService.analyse(analyse);

        analyse.setRiskPoint(risk);

        Long longRisk = (long) (risk*100);

        // 若有animalId，则保存到数据库中
        if(analyse.getAnimalId() != null && analyse.getAnimalId() != 0){
            Animal animal = animalMapper.selectById(analyse.getAnimalId());
            if(animal == null){
                throw new RuntimeException("动物不存在："+analyse.getAnimalId());
            }
            animal.setRiskPoint(longRisk);
            animalMapper.updateById(animal);
        }
        return analyse;
    }

    @Operation(description = "分析动物危险性，并添加到数据库")
    @PostMapping("/analyse")
    public Analyse analyseDog(@RequestBody AnalyseRequest analyseRequest) throws JsonProcessingException {
        // 保存动物数据到数据库
        Animal animal = analyseRequest.toAnimal();
        animalMapper.insert(animal);

        // 转换为Analyse数据
        Analyse analyse = analyseRequest.toAnalyse();

        // 获取物种信息
        Species species = speciesMapper.selectById(analyseRequest.getSpeciesId());
        if(species!=null){
            analyse.setSpecies(species);
        }

        final String[] analyseResult = new String[1];
        // 评估动物危险性
        String animalInfo = oobjectMapper.writeValueAsString(analyse);
        deepSeekService.chatWithDeepseek(animalInfo, new DataReceivedCallback() {
            @Override
            public void onDataReceived(String newData) {
                System.out.println(newData);
            }

            @Override
            public void onProcessCompleted(String fullContent) {
                System.out.println(fullContent);
                analyseResult[0] = fullContent;
            }

            @Override
            public void onError(Exception error) {
                error.printStackTrace();
            }
        });

        // 解析json信息
        Map<String,Object> map = oobjectMapper.readValue(analyseResult[0], Map.class);
        Integer risk = (Integer) map.get("risk");
        String des = (String) map.get("description");

        analyse.setRiskPoint(risk);
        analyse.setRiskDescription(des);

        analyseMapper.insert(analyse);
        return analyse;
    }

    @Operation(summary = "获取全部已经分析过的动物危险性数据")
    @GetMapping("/analyse/getAll")
    public List<Analyse> getAllAnalyse(){
        return analyseMapper.selectList(null);
    }

    @Operation(summary = "删除全部已经分析过的动物危险性数据")
    @GetMapping("/analyse/deleteAll")
    public boolean deleteAll(HttpServletRequest request){
        log.warn("删除全部动物危险性数据：{}", RequestUtils.getRequestInfo(request));
        return analyseMapper.delete(null) > 0;
    }

    @Operation(summary = "根据id删除动物危险性数据")
    @GetMapping("/analyse/deleteById")
    public boolean deleteDogById(Long id,HttpServletRequest request){
        log.warn("根据id删除动物危险性数据：{}", RequestUtils.getRequestInfo(request));
        return analyseMapper.deleteById(id) > 0;
    }


}
